package com.macro.mall.demo.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.es.EsAddDocDto;
import com.macro.mall.common.es.EsDelDocDto;
import com.macro.mall.demo.service.EsQueryService;
import com.macro.mall.model.EsQueryAndPage;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author：hwh
 * @Description: Elasticsearch Document Controller
 * @name：EsDocController
 * @Date：2024/10/16 16:59
 */
@RestController
@RequestMapping("/esQuery")
public class EsQueryController {

    private static final Logger logger = LoggerFactory.getLogger(EsQueryController.class);
    private final EsQueryService esDocService;

    @Autowired
    public EsQueryController(EsQueryService esDocService) {
        this.esDocService = esDocService;
    }

    /**
     * 批量添加文档
     * @param esAddDocDto 包含要添加的文档信息
     * @return CommonResult
     */
    @PostMapping("/batchSave")
    public ResponseEntity<CommonResult<String>> batchSave(@Validated @RequestBody EsAddDocDto esAddDocDto) {
        logger.info("开始批量添加文档，数据：{}", esAddDocDto);
        esDocService.batchSave(esAddDocDto);
        logger.info("批量添加文档成功");
        return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.success("数据添加成功"));
    }

    /**
     * 批量删除文档
     * @param esDelDocDto 包含要删除的文档ID信息
     * @return CommonResult
     */
    @DeleteMapping("/delete")
    public ResponseEntity<CommonResult<String>> deleteEsDoc(@Validated @RequestBody EsDelDocDto esDelDocDto) {
        logger.info("开始批量删除文档，数据：{}", esDelDocDto);
        esDocService.deleteEsDoc(esDelDocDto);
        logger.info("批量删除文档成功");
        return ResponseEntity.ok(CommonResult.success("删除成功"));
    }

    /**
     * 查询文档
     * @param esQueryAndPage 查询条件及分页信息
     * @return CommonResult<List<Object>>
     */
    @Operation(summary = "查询文档")
    @PostMapping("/query")
    public ResponseEntity<CommonResult<List<Object>>> listEsDoc(@RequestBody EsQueryAndPage esQueryAndPage) {
        logger.info("开始查询文档，条件：{}", esQueryAndPage);
        List<Object> list = esDocService.query(esQueryAndPage);
        logger.info("查询文档成功，返回结果数量：{}", list.size());
        return ResponseEntity.ok(CommonResult.success(list));
    }
}
